package at.fhooe.im440.pandora.events;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import at.fhooe.im440.core.Core;

public class EventManager {
	
	private HashMap<String, List<EventListener>> listenerMap = new HashMap<String, List<EventListener>>();
	private List<Event> pendingEvents = new ArrayList<Event>();
	private Core core;
	
	public EventManager(Core c){
		core = c;
	}

	public void addListener(EventListener e, String type) {
		List<EventListener> listeners = listenerMap.get(type);
		if (listeners == null) {
			listeners = new ArrayList<EventListener>();
			listenerMap.put(type, listeners);
		}
		
		listeners.add(e);
	}

	
	// 2 Listen - doppel list
	// oder
	// andere Abarbeitung - immer erstes Event nehmen v
	// Linked List
	
	public void addEvent(Event event) {
		pendingEvents.add(event);	
	}

	public void removeEvent(Event e) {
		pendingEvents.remove(e);
	}
	
	public void handleEvents() {
		for (Event event : this.pendingEvents) {
			System.out.print(event.getType());
			fireEvent(event);
		}
		
		this.pendingEvents.clear();
	}

	private void fireEvent(Event event) {
		List<EventListener> listeners = listenerMap.get(event.getType());
		
		if (listeners == null) {
			return;
		}
		
		for (EventListener listener : listeners) {
			event.processEvent(listener);
		}
	}	
}

